package com.start.autumn.springUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@Slf4j
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringUtil.context = context;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (clazz == null) {
            return null;
        }
        return context.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        if (name == null || name.isEmpty() || clazz == null) {
            return null;
        }
        return context.getBean(name, clazz);
    }

    public static Object getBean(String name) {
        if (name == null || name.isEmpty()) {
            return null;
        }
        return context.getBean(name);
    }

    public static ApplicationContext getContext() {
        if (context == null) {
            log.error("SpringUtil.getContext() is null");
            return null;
        }
        return context;
    }
}
